<template>
  <div class="user-manage">
    <div class="query-form">
      <el-form ref="form" :inline="true" :model="queryForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="queryForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getRoleList">查询</el-button>
          <el-button @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="handleAdd(1)">创建</el-button>
      </div>
      <el-table
        :data="roleList"
      >
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="item.formatter"
        >
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="{row}">
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button  size="mini"
              @click="handleOpenPermission(row)"
              >设置权限</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDel(row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
     <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :total="pager.total"
        :page-size="pager.pageSize"
        @current-change="handleCurrentChange"
      />
    </div>
      <!-- 创建 -->
     <el-dialog title="角色创建" v-model="showModal">
      <el-form
        ref="dialogForm"
        :model="roleForm"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
          type="textarea" 
          :rows="2"
          v-model="roleForm.remark" 
          placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog> 

    <!-- 设置权限 -->
     <el-dialog title="设置权限" v-model="showPermission">
      <el-form
        label-width="100px"
      >
        <el-form-item label="角色名称" >
         {{currentRoleName}}
        </el-form-item>
        <el-form-item label="选择权限" >
          <el-tree 
            ref="tree"
            :data="menuList" 
            node-key="_id"  
            :props="{label:'menuName'}"
            show-checkbox 
            default-expand-all
          >
           </el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPermission=false">取 消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog> 
  </div>
</template>
<script>
import utils from "../utils/utils";
export default {
  name: "role",
  data() {
    return {
      queryForm: {
        roleName: '',
      },
      roleList: [],
      columns: [
        {
          label: "角色名称",
          prop: "roleName",
          width: 150,
        },
        {
          label: "备注",
          prop: "remark",
        },
        {
          label: "权限列表",
          prop: "permissionList",
          formatter:(row,columns,value )=>{
            let names = []
            let list = value.halfCheckedKeys || [];
            list.map(key=>{
              if(key)names.push(this.actionMap[key])
            })
            return names.join(',')
          }
        },
        {
          label: "创建时间",
          prop: "createTime",
          formatter(row, column, value) {
            return utils.formateDate(new Date(value));
          },
        },
      ],
      pager:{
       total:0,
       pageSize: 10,
      },
      showModal:false,
      roleForm:{},
      rules: {
        roleName: [
          {
            required: true,
            message: "请输入菜单名称",
            trigger: "blur",
          },
        ],
      },
      action:'',
      showPermission:false,
      currentRoleName:'',
      currentId:'',
      menuList:[],
      actionMap:{}
    };
  },
  mounted() {
    this.getRoleList();
    this.getMenuList();
  },
  methods: {
    // 角色列表初始化
    async getRoleList() {
      try {
        let {list ,page}= await this.$api.getRoleList(this.queryForm);
        this.roleList = list;
        this.pager.total = page.total
      } catch (e) {
        throw new Error(e);
      }
    },
    // 菜单列表初始化
    async getMenuList(){
      try {
        let list= await this.$api.getMenuList();
        this.menuList = list;
        this.getActionMap(list)
      } catch (e) {
        throw new Error(e);
      }
    },
    // 表单重置
    handleReset(form) {
      this.$refs[form].resetFields();
    },
    handleAdd(){
      this.action = 'add'
      this.showModal=true
    },
    handleEdit(row){
      this.action = 'edit'
      this.showModal = true
      this.$nextTick(()=>{
         Object.assign(this.roleForm, row);
      })
    },
    async handleDel(_id){
      await this.$api.roleOperate({_id,action:'delete'})  
      this.$message.success('删除成功');
      this.getRoleList();
    },
    handleClose(){
      this.handleReset('dialogForm')
      this.showModal=false
    },
    handleSubmit(){
      this.$refs.dialogForm.validate(async valid=>{
        if(valid){
          let {roleForm,action} = this;
          let params = {...roleForm,action};
          await this.$api.roleOperate(params);
          this.$message.success('创建成功');
          this.handleClose();
          this.getRoleList();
        }
      })
    },
    handleCurrentChange(){

    },
    handleOpenPermission(row){
      this.currentRoleName = row.roleName
      this.currentId = row._id
      this.showPermission = true
      let {checkedKeys} = row.permissionList;
      setTimeout(()=>{
        this.$refs.tree.setCheckedKeys(checkedKeys)
      })

    },
    handleCheckChange(){

    },
    async  handlePermissionSubmit(){
      let nodes = this.$refs.tree.getCheckedNodes();
      let halfKey = this.$refs.tree.getHalfCheckedKeys();
      let checkedKeys = []
      let parentKeys = []
      nodes.map(node=>{
        if(!node.children){
          checkedKeys.push(node._id)
        }else {
          parentKeys.push(node._id)
        }
      })
      let params = {
        _id:this.currentId,
        permissionList:{
          checkedKeys,
          halfCheckedKeys:parentKeys.concat(halfKey)
        }
      }
      await this.$api.updatePermission(params)
      this.showPermission =false
      this.$message.success('提交成功')
      this.getRoleList()
    },
    getActionMap(list){
      let actionMap = {}
      const deep = (arr)=>{
        while(arr.length){
          let item = arr.pop()
          if(item.children && item.action){
            actionMap[item._id] = item.menuName
          }
          if(item.children&& !item.action){
            deep(item.children)
          }
        }
      }
      deep(JSON.parse(JSON.stringify(list)))
      this.actionMap = actionMap
    }
  },
};
</script>

<style lang="scss">
</style>